<!--
ImageEditorModal 组件使用说明：

Props:
- visible: Boolean - 控制弹窗显示/隐藏
- imageUrl: String - 要编辑的图片URL

Events:
- update:visible - 双向绑定visible状态
- close - 弹窗关闭事件
- save - 保存图片事件，参数为图片的dataURL

使用示例：
<template>
  <div>
    <button @click="showEditor = true">编辑图片</button>

    <ImageEditorModal
      v-model:visible="showEditor"
      :image-url="currentImageUrl"
      @close="handleClose"
      @save="handleSave"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import ImageEditorModal from '@/components/common/ImageEditorModal.vue'

const showEditor = ref(false)
const currentImageUrl = ref('')

const handleClose = () => {
  console.log('编辑器已关闭')
}

const handleSave = (dataURL) => {
  console.log('保存的图片dataURL:', dataURL)
  // 这里可以处理保存逻辑，如上传到服务器等
}
</script>
-->

<template>
  <teleport to="body">
    <transition name="modal-fade">
      <div v-if="visible" class="image-editor-modal-overlay" @click="handleClose">
        <div class="image-editor-modal-content" @click.stop>
          <!-- 关闭按钮 -->
          <div class="modal-close-btn" @click="handleClose">
            <el-icon><Close /></el-icon>
          </div>

          <!-- 图片编辑器容器 -->
          <div class="modal-editor-container">
            <ImageEditor
              v-if="currentImageUrl"
              ref="imageEditorRef"
              :image-url="currentImageUrl"
              :width="editorWidth"
              :height="editorHeight"
              :business-id="businessId"
              :business-type="businessType"
              :roles="roles"
              :drama-id="dramaId"
              :is-record-expanded="!isRecordCollapsed"
              @image-loaded="handleImageLoaded"
              @generation-completed="handleGenerationCompleted"
            />
            <div class="record-wrapper" :class="{ 'collapsed': isRecordCollapsed }" style="position: relative; z-index: 1000;">
              <!-- 收起状态：只显示icon -->
              <div v-if="isRecordCollapsed" class="record-collapsed-icon" @click="toggleRecordPanel">
                <img src="@/assets/images/right_line.png" class="record-icon-img collapsed-icon" />
              </div>
              
              <!-- 展开状态：显示完整面板 -->
              <template v-else>
                <div class="record-header" @click="toggleRecordPanel">
                  <img src="@/assets/images/right_line.png" class="record-header-img expanded-icon" />
                  <div class="record-header-title-wrapper">
                    <div class="record-header-title">生图记录</div>
                    <div class="record-header-count">{{ records.length }}</div>
                  </div>
                </div>
                <div class="record-content">
                  <div v-if="isLoadingRecords" class="record-loading">
                    <div class="loading-text">加载中...</div>
                  </div>
                  <div v-else-if="records.length === 0" class="record-empty">
                    <div class="empty-text">暂无生图记录</div>
                  </div>
                  <div v-else class="record-item" v-for="(record, index) in records" :key="index" @click="replaceWithRecord(record)">
                    <img :src="record.originalUrl" class="record-item-img" />
                    <div class="record-item-prompt">{{ record.fileType === 'IMAGE' ? '分镜图' : '消除场景图' }}{{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}</div>
                    <div class="hover-prompt">{{ record.fileType === 'IMAGE' ? '分镜图' : '消除场景图' }}{{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}</div>
                    <el-button class="save-btn" color="#1c1d29" @click.stop="saveImage(record)">{{businessType !== 'STORYBOARD' ? '保存' : '添加'}}</el-button>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </teleport>
</template>

<script setup>
import { ref, watch, computed, onMounted, onUnmounted } from 'vue'
import ImageEditor from './ImageEditor.vue'
import { Close } from '@element-plus/icons-vue'
import { imageGenerationRecord } from '@/api/drama'
import dayjs from 'dayjs'

const saveImage = (record) => {
  console.log('保存图片:', record)
  // 触发save事件，传递record数据给调用者
  emit('save', {
    fileKey: record.fileKey,
    originalUrl: record.originalUrl,
    record: record
  })
}

// 用记录中的图片替换当前画布图片
const replaceWithRecord = async (record) => {
  if (!record || !record.originalUrl) {
    console.warn('记录数据无效或缺少图片URL')
    return
  }
  
  try {
    console.log('替换为记录图片:', record.originalUrl)
    
    // 更新当前图片URL
    currentImageUrl.value = record.originalUrl
    
    // 如果ImageEditor引用存在且有replaceImageAndReset方法，调用它
    if (imageEditorRef.value && typeof imageEditorRef.value.replaceImageAndReset === 'function') {
      await imageEditorRef.value.replaceImageAndReset(record.originalUrl)
      console.log('已替换为记录图片并重置编辑器')
    } else {
      console.warn('ImageEditor引用不存在或缺少replaceImageAndReset方法')
    }
    
  } catch (error) {
    console.error('替换图片失败:', error)
  }
}

// Props定义
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  imageUrl: {
    type: String,
    default: ''
  },
  businessId: {
    type: String,
    default: ''
  },
  businessType: {
    type: String,
    default: 'STORYBOARD'
  },
  roles: {
    type: Array,
    default: () => []
  },
  dramaId: {
    type: String,
    default: ''
  }
})

// Emits定义
const emit = defineEmits(['update:visible', 'close', 'save', 'generation-completed'])

const records = ref([])
const isLoadingRecords = ref(false)
const isRecordCollapsed = ref(true) // 记录面板是否收起，默认收起

// Template refs
const imageEditorRef = ref(null)

// 当前显示的图片URL（内部管理，可以动态更改）
const currentImageUrl = ref('')

// 计算属性 - 使用与画布相同的尺寸逻辑
const editorWidth = computed(() => {
  return window.innerWidth - 100 - 16
})

const editorHeight = computed(() => {
  return window.innerHeight - 68
})

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 弹窗打开时的处理
    document.body.style.overflow = 'hidden'
    // 初始化当前图片URL
    currentImageUrl.value = props.imageUrl
    // 获取生图记录
    fetchRecords()
  } else {
    // 弹窗关闭时的处理
    document.body.style.overflow = ''
  }
})

// 监听imageUrl prop变化
watch(() => props.imageUrl, (newImageUrl) => {
  if (newImageUrl) {
    currentImageUrl.value = newImageUrl
  }
})

// 处理关闭
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}

// 处理保存
const handleSave = () => {
  if (imageEditorRef.value) {
    const dataURL = imageEditorRef.value.exportImage()
    emit('save', dataURL)
  }
}

// 切换记录面板展开/收起状态
const toggleRecordPanel = () => {
  isRecordCollapsed.value = !isRecordCollapsed.value
}

// 获取生图记录
const fetchRecords = async () => {
  try {
    isLoadingRecords.value = true
    console.log('开始获取生图记录...')
    
    const params = {
      pageNum: 1,
      pageSize: 1000
    }
    
    const response = await imageGenerationRecord(params)
    console.log('生图记录响应:', response)
    
    if (response.data && response.data.records) {
      records.value = response.data.records
      console.log(`获取到${records.value.length}条生图记录`)
    } else {
      console.warn('生图记录响应格式异常:', response)
      records.value = []
    }
  } catch (error) {
    console.error('获取生图记录失败:', error)
    records.value = []
  } finally {
    isLoadingRecords.value = false
  }
}

// 处理图片加载完成
const handleImageLoaded = () => {
  // 可以在这里添加图片加载完成后的处理逻辑
}

// 处理生成完成事件
const handleGenerationCompleted = (eventData) => {
  console.log('生成操作完成:', eventData)
  
  // 重新获取生图记录以刷新列表
  fetchRecords()
  
  // 将事件传递给父组件
  emit('generation-completed', eventData)
  
  console.log(`${eventData.type === 'redraw' ? '重绘' : '消除'}操作完成，已刷新生图记录`)
}

// 窗口大小变化处理
const handleResize = () => {
  // 当窗口大小改变时，ImageEditor组件会自动重新计算尺寸
  // 这里不需要额外处理，因为计算属性会自动更新
}

// 组件挂载时初始化
onMounted(() => {
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  document.body.style.overflow = ''
  // 移除窗口大小监听器
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
/* 弹窗动画 */
.modal-fade-enter-active,
.modal-fade-leave-active {
  transition: opacity 0.3s ease;
}

.modal-fade-enter-from,
.modal-fade-leave-to {
  opacity: 0;
}

.modal-fade-enter-to,
.modal-fade-leave-from {
  opacity: 1;
}

/* 遮罩层样式 */
.image-editor-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  backdrop-filter: blur(2px);
}

/* 弹窗内容样式 */
.image-editor-modal-content {
  position: relative;
  width: calc(100vw - 100px);
  height: 100vh;
  background: #f8f9fa;
  border-top-left-radius: 12px;
  border-bottom-left-radius: 12px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  margin-left: 100px;
}

/* 关闭按钮样式 */
.modal-close-btn {
  position: absolute;
  top: 8px;
  left: -40px;
  width: 32px;
  height: 32px;
  background: rgba(0, 0, 0, 0.1);
  border: none;
  border-radius: 50%;
  background: #EBEDF2;
  box-shadow: 0px 0px 16px 0px #7F839426;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1001;
  color: #666;
}

.modal-close-btn svg {
  width: 20px;
  height: 20px;
}

/* 编辑器容器样式 */
.modal-editor-container {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  background: #F5F6FA;
  overflow: hidden;
  border-top-left-radius: 12px;
  border-bottom-left-radius: 12px;
  padding: 16px;
}

/* 记录样式 */
.record-wrapper {
  width: 220px;
  height: 100%;
  background: #fff;
  border-radius: 8px;
  padding: 12px;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
}

.record-wrapper.collapsed {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  justify-content: center;
  align-items: center;
  box-shadow: 0px 0px 16px 0px rgba(127, 131, 148, 0.15);
}

/* 收起状态的icon */
.record-collapsed-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.record-collapsed-icon:hover {
  background: rgba(162, 166, 184, 0.1);
}

.record-icon-img {
  width: 16px;
  height: 16px;
  transition: transform 0.3s ease;
}

/* icon旋转状态 */
.collapsed-icon {
  transform: rotate(180deg);
}

.expanded-icon {
  transform: rotate(0deg);
}
.record-content {
  flex: 1;
  overflow-y: auto;
}
.record-header {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  padding: 4px;
  border-radius: 6px;
  margin: -4px;
  transition: all 0.2s ease;
}

.record-header:hover {
  background: rgba(162, 166, 184, 0.1);
}
.record-header-img {
  width: 16px;
  height: 16px;
}
.record-header-title-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex: 1;
}
.record-header-title {
  font-size: 14px;
  color: var(--text-color-primary);
}
.record-header-count {
  font-size: 12px;
  color: var(--text-color-2);
}
.record-item {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 6px;
  border-radius: 8px;
  margin-top: 16px;
  transition: all 0.2s ease;
}
.record-item:hover {
  background: rgba(162, 166, 184, 0.1);
  transform: translateY(-1px);
}
.record-item:active {
  transform: translateY(0);
}
.record-item:hover .record-item-prompt{
  display: none;
}
.hover-prompt {
  display: none;
  flex: 1;
  font-size: 14px;
  color: var(--text-color-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.record-item:hover .hover-prompt{
  display: block;
}
.save-btn {
  display: none;
}
.record-item:hover .save-btn{
  display: block;
}
.record-item-img {
  width: 48px;
  height: 85px;
  object-fit: cover;
  border-radius: 4px;
}
.record-item-prompt {
  font-size: 14px;
  color: var(--text-color-primary);
}

/* 加载和空状态样式 */
.record-loading,
.record-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 16px;
  text-align: center;
}

.loading-text,
.empty-text {
  font-size: 14px;
  color: var(--text-color-2);
}

.modal-editor-container :deep(.image-editor) {
  max-width: 100%;
  max-height: 100%;
  border-radius: 8px;
}

/* 底部按钮样式 */
.modal-footer {
  padding: 16px 24px;
  background: white;
  border-top: 1px solid #e1e5e9;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.modal-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 80px;
}

.modal-btn-cancel {
  background: #f5f5f5;
  color: #666;
  border: 1px solid #d9d9d9;
}

.modal-btn-cancel:hover {
  background: #e8e8e8;
  border-color: #bfbfbf;
}

.modal-btn-primary {
  background: #409eff;
  color: white;
  border: 1px solid #409eff;
}

.modal-btn-primary:hover {
  background: #337ecc;
  border-color: #337ecc;
}

.modal-btn:active {
  transform: translateY(1px);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .image-editor-modal-content {
    width: calc(100vw - 40px);
    height: calc(100vh - 40px);
  }
}

@media (max-width: 768px) {
  .image-editor-modal-content {
    width: calc(100vw - 20px);
    height: calc(100vh - 20px);
  }

  .modal-footer {
    padding: 12px 16px;
  }
}
</style>
